<?php
/**
 * 控制器基类
 * @author sundongdong
 *
 */
class Controller_Base extends Zend_Controller_Action {
	//初始化控制器公用对象
	public $smarty; //模版类
	public $module; //当前模块名称
	public $action; //当前ACTION名称
	public $controller; //当前控制器名称
	public $config; //当前模块配置信息[全部]
	public $client; //当前客户端IP地址
	protected $auth; // 当前登录者的权限
	/**
	 *
	 * {@inheritDoc}
	 * @see Zend_Controller_Action::init()
	 */
	public function init() {
		//获取模块名称
		$_name = $this->getRequest()->getModuleName();

		//获取Action名称
		$_action = $this->getRequest()->getActionName();

		//获取Controller名称
		$_controller = $this->getRequest()->getControllerName();

		//获取客户端IP地址
		$_ip = $this->getRequest()->getClientIp();

		//注册到全局对象
		Zend_Registry::set('_module', strtolower($_name));
		Zend_Registry::set('_action', strtolower($_action));
		Zend_Registry::set('_controller', strtolower($_controller));
		Zend_Registry::set('_ip', strtolower($_ip));

		//初始化当前Modules
		$this->module = $_name;
		//初始化当前Action
		$this->action = $_action;
		//初始化当前Controller
		$this->controller = $_controller;
		//初始化当前客户端IP地址
		$this->client = $_ip;

		// 初始化默认配置文件
		$this->config = Helper_Config::get('base');
		// 初始化Smarty
		$smarty = Zend_Registry::get('smarty');

		// 设置Smarty模板路径
		$smarty->setCompileDir(APPLICATION_PATH . '/../templates_c/' . $_name . '/compile_c');
		$smarty->setCacheDir(APPLICATION_PATH . '/../templates_c/' . $_name . '/cache_c');
		$smarty->setTemplateDir(APPLICATION_PATH . '/modules/' . $_name . '/views/templates');
		$smarty->assign('js', isset($this->config['js']['url']) ? $this->config['js']['url'] : '');
		$smarty->assign('css', isset($this->config['css']['url']) ? $this->config['css']['url'] : '');
		$smarty->assign('web', isset($this->config['web']['url']) ? $this->config['web']['url'] : '');
		$smarty->assign('img', isset($this->config['img']['url']) ? $this->config['img']['url'] : '');
		$smarty->assign('fonts', isset($this->config['fonts']['url']) ? $this->config['fonts']['url'] : '');
		$smarty->assign('root', (isset($global_config->root->url) ? $global_config->root->url : ''));

		// 重新初始化smarty对象
		$this->smarty = $smarty;
		// 检查权限

		//面包屑
		@$this->getBreads();

		$this->_session = Zend_Registry::get('_session');
	}
	//获取当前页面面包屑
	public function getBreads() {
		$menuApi = new Application_Model_Privilege();
		$breads = $menuApi->getBreads($this->module, $this->controller, $this->action);
		$this->smarty->assign('bread', $breads);
	}

	/**
	 * 跳转到登陆验证中心
	 * @param  string $loginSuccessReturnUrl  登陆成功跳转地址
	 * @return [type]                        [description]
	 */
	protected function _ssoLogin($loginSuccessReturnUrl = "") {
		$ssoHost = Helper_Config::get('base', 'sso', 'host');
		$returnUrl = $loginSuccessReturnUrl == "" ? "http://" . getenv('HTTP_HOST') . getenv('REQUEST_URI') : ("http://" . getenv('HTTP_HOST') . $loginSuccessReturnUrl);
		$checkUrl = "http://" . getenv('HTTP_HOST') . "/index/login/check";
		$strurli = base64_encode($checkUrl . '|' . $returnUrl);
		$url = $ssoHost . '/login/index/sso/?struli=' . $strurli . '&from=ifs';
		echo "<script type='text/javascript'>location.href='{$url}'</script>";
		exit(1);
	}

	/**
	 * 接口加密函数
	 */
	protected function md5Encrypt($input) {
		$key = Helper_Config::get('base', 'crypt', 'key');
		$input = (string) $input;
		return md5($key . $input);
	}

	/**
	 * 取得所有事业部分类 递归HTML树状
	 * @param 数据
	 * @param 父ID
	 * @param 长度标识
	 * @return string
	 */
	public function getTreeDepts($data, $pid = 0, $len = 0) {

		static $str = '';
		$len++;
		foreach ($data as $values) {
			$pid == 0 && $len = 0;
			if ($values['parent_id'] == $pid) {
				$str .= '<option value="' . $values['department_id'] . '" data-pid="' . $values['parent_id'] . '">' .
				str_repeat('--', $len) . '| ' . $values['department_name'] . '</option>';
				$this->getTreeDepts($data, $values['department_id'], $len);
			}
		}
		return $str;
	}

	/**
	 * 整理GET过来的分页数据
	 */
	protected function _PAGELIMITER(&$page, $count = 15) {

		$page = $this->_request->getParams();
		$page['action'] = isset($page['page_size']) ? $page['page_size'] : $count;
		$page['page'] = isset($page['page']) ? $page['page'] : 0;
		$page['first'] = $page['page'] * $page['action'] - $page['action'];
		$page['first'] < 0 && $page['first'] = 0;
		return ['limit' => ' limit ' . $page['first'] . ',' . $page['action']];
	}

	/**
	 * JSON转换
	 * @param 数据：字符串等需要转换的类型
	 * @param 转换方式：1-encode 2-decode 1是输出 2返回
	 * @return [type]       [description]
	 */
	function renderJson($data, $type = 1) {

		if ($type == 1) {
			exit(json_encode($data));
		}
		return json_decode($data);
	}
	/**
	 * 向用户显示敏感的应用程序错误信息(此处只需抛出异常，错误处理插件会自动捕获显示)
	 * @param  [type] $errorMsg 错误信息
	 * @return void
	 */
	public function showError($errorMsg) {
		throw new Exception($errorMsg, -500);
	}

	/**
	 * 适用于二维数组的字段替换方法 通过本方式转换从接口过来的数据到新数组
	 * @param 源数据
	 * @param 新数据结构 通过该结构转换形成新的数组
	 * @param 存表名称
	 * @param 存储方式 1-更新；2-存储；3-更新或存储
	 * @param 更新时指定的字段
	 * @return array
	 */
	public function mapping($dataFrom, $structure, $clumn, $type = 3, $pk = 'id') {

		$insertVar = '';
		$arr = [];
		foreach ($dataFrom as $key => $values) {
			$update = 'UPDATE ' . $clumn . ' SET ';
			$insertFirst = '(';
			$updateVar = '';
			$insertVar .= '(';
			$duplicate = '';
			foreach ($structure as $k => $v) {
				// 如果能对应这个键
				if (isset($values[$k])) {
					$insertFirst .= $v . ',';
					!is_numeric($values[$k]) && $values[$k] = '"' . $values[$k] . '"';
					$updateVar .= $v . '=' . $values[$k] . ', ';
					$insertVar .= $values[$k] . ',';
					$duplicate .= $v . ' = ' . 'VALUES(' . $v . '), ';
				}
			}
			$insertVar = rtrim($insertVar, ',');
			$insertVar .= '), ';
			$insertFirst = rtrim($insertFirst, ',');
			$insertFirst .= ') VALUES ';
			if ($type == 1) {
				$arr['update'][] = $update .= rtrim($updateVar, ', ');
			}
		}
		$insert = 'INSERT INTO ' . $clumn;
		if ($type == 2) {
			$arr['insert'] = $insert . $insertFirst . rtrim($insertVar, ', ');
		} else if ($type == 3) {
			$arr['insertOnDuplicate'] = $insert . $insertFirst . rtrim($insertVar, ', ') . ' ON DUPLICATE KEY UPDATE ' . rtrim($duplicate, ', ');
		}
		return $arr;
	}
}